<template>
  <div class="code-converter">
    <div class="container">
      <div class="input-section">
        <div class="card">
          <div class="card-header">
            <h2>源代码</h2>
            <div class="shortcut-tips">
              <div class="tip">
                <span class="shortcut-key">Tab</span>
                <span class="tip-text">缩进</span>
              </div>
              <div class="tip">
                <span class="shortcut-key">Shift + Tab</span>
                <span class="tip-text">反缩进</span>
              </div>
              <div class="tip">
                <span class="shortcut-key">Ctrl + /</span>
                <span class="tip-text">注释/取消注释</span>
              </div>
            </div>
          </div>
          <textarea
            v-model="sourceCode"
            class="code-input"
            placeholder="在此输入您的代码..."
            @keydown="handleKeyDown"
          ></textarea>
          <div class="card-footer">
            <button @click="convertCode" class="convert-btn">
              <span class="btn-icon">⚡</span>
              转换代码
            </button>
          </div>
        </div>
      </div>
      
      <div class="output-section">
        <div class="card">
          <div class="card-header">
            <h2>转换结果</h2>
            <div class="font-settings">
              <div class="setting-group">
                <label>中文字体:</label>
                <select v-model="chineseFontFamily" class="font-select">
                  <option value="SimSun">宋体</option>
                  <option value="Microsoft YaHei">微软雅黑</option>
                  <option value="KaiTi">楷体</option>
                  <option value="SimHei">黑体</option>
                </select>
                <input type="number" v-model="chineseFontSize" min="8" max="24" class="font-size-input" />
                <span>pt</span>
              </div>
              <div class="setting-group">
                <label>英文字体:</label>
                <select v-model="englishFontFamily" class="font-select">
                  <option value="Consolas">Consolas</option>
                  <option value="Courier New">Courier New</option>
                  <option value="Arial">Arial</option>
                  <option value="Times New Roman">Times New Roman</option>
                </select>
                <input type="number" v-model="englishFontSize" min="8" max="24" class="font-size-input" />
                <span>pt</span>
              </div>
            </div>
            <button @click="copyToClipboard" class="copy-btn">
              <span class="btn-icon">📋</span>
              复制
            </button>
          </div>
          <div class="word-style-output" ref="outputContainer">
            <table class="code-table">
              <tbody>
                <tr v-for="(line, index) in codeLines" :key="index">
                  <td class="line-number">{{ index + 1 }}</td>
                  <td class="code-content">{{ line }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加复制成功提示 -->
    <transition name="fade">
      <div v-if="showCopySuccess" class="copy-success">
        代码已成功复制到剪贴板！
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'CodeConverter',
  data() {
    return {
      sourceCode: '',
      codeLines: [],
      showCopySuccess: false,
      chineseFontFamily: 'SimSun',
      englishFontFamily: 'Consolas',
      chineseFontSize: 9,
      englishFontSize: 9,
      commentSymbols: {
        javascript: { line: '//' },
        python: { line: '#' },
        java: { line: '//' },
        cpp: { line: '//' },
        csharp: { line: '//' }
      }
    }
  },
  methods: {
    convertCode() {
      this.codeLines = this.sourceCode.split('\n')
    },
    handleKeyDown(e) {
      if (e.key === 'Tab') {
        e.preventDefault()
        
        const textarea = e.target
        const start = textarea.selectionStart
        const end = textarea.selectionEnd
        const value = textarea.value
        
        // 获取选中区域的开始行和结束行
        const beforeStart = value.substring(0, start)
        const afterEnd = value.substring(end)
        const selectedText = value.substring(start, end)
        const startLinePos = beforeStart.lastIndexOf('\n') + 1
        const endLinePos = start + selectedText.length
        const hasSelection = start !== end
        
        if (hasSelection) {
          // 多行处理
          const selectedLines = selectedText.split('\n')
          const newText = selectedLines.map(line => {
            if (e.shiftKey) {
              // 反缩进：如果行以制表符或2个空格开头，则移除
              return line.replace(/^(\t|  )/, '')
            } else {
              // 缩进：在每行开头添加制表符
              return '\t' + line
            }
          }).join('\n')
          
          const newValue = value.substring(0, start) + newText + value.substring(end)
          this.sourceCode = newValue
          
          // 恢复选区
          this.$nextTick(() => {
            textarea.selectionStart = start
            textarea.selectionEnd = start + newText.length
          })
        } else {
          // 单行处理
          if (e.shiftKey) {
            // 反缩进：如果当前行以制表符或2个空格开头，则移除
            const currentLine = value.substring(startLinePos, endLinePos)
            if (/^(\t|  )/.test(currentLine)) {
              const newValue = value.substring(0, startLinePos) + 
                             currentLine.replace(/^(\t|  )/, '') + 
                             value.substring(endLinePos)
              this.sourceCode = newValue
              // 设置光标位置
              this.$nextTick(() => {
                textarea.selectionStart = textarea.selectionEnd = start - 1
              })
            }
          } else {
            // 插入制表符
            const newValue = value.substring(0, start) + '\t' + value.substring(end)
            this.sourceCode = newValue
            // 设置光标位置
            this.$nextTick(() => {
              textarea.selectionStart = textarea.selectionEnd = start + 1
            })
          }
        }
      }
      
      // 处理注释快捷键
      if (e.key === '/' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault()
        
        const textarea = e.target
        const start = textarea.selectionStart
        const end = textarea.selectionEnd
        const value = textarea.value
        
        // 获取当前语言的注释符号
        const symbol = (this.commentSymbols[this.selectedLanguage] || this.commentSymbols.javascript).line
        
        // 行注释 (Ctrl + /)
        this.toggleLineComment(start, end, value, symbol)
      }
    },
    toggleLineComment(start, end, value, commentSymbol) {
      const lines = value.split('\n')
      let startLine = value.substring(0, start).split('\n').length - 1
      let endLine = value.substring(0, end).split('\n').length - 1
      
      // 检查选中的行是否都已经有注释
      const allCommented = lines
        .slice(startLine, endLine + 1)
        .every(line => line.trimStart().startsWith(commentSymbol))
      
      // 更新行
      const updatedLines = lines.map((line, i) => {
        if (i >= startLine && i <= endLine) {
          if (allCommented) {
            // 移除注释
            return line.replace(new RegExp(`^(\\s*)${commentSymbol}\\s?`), '$1')
          } else {
            // 添加注释
            return line.replace(/^(\s*)/, `$1${commentSymbol} `)
          }
        }
        return line
      })
      
      // 更新文本
      this.sourceCode = updatedLines.join('\n')
      
      // 恢复选区
      this.$nextTick(() => {
        const newText = this.sourceCode
        const newStart = newText.split('\n').slice(0, startLine).join('\n').length + 
                        (startLine > 0 ? 1 : 0)
        const newEnd = newText.split('\n').slice(0, endLine + 1).join('\n').length
        textarea.selectionStart = newStart
        textarea.selectionEnd = newEnd
      })
    },
    copyToClipboard() {
      // 在控制台输出复制的文本
      console.log('复制的文本内容：')
      this.codeLines.forEach((line, index) => {
        console.log(`${(index + 1).toString().padStart(3, ' ')}. ${line}`)
      })
      
      const tempDiv = document.createElement('div')
      
      const processLine = (line) => {
        if (!line) return '&nbsp;'
        return line
          .replace(/\s/g, (match) => {
            if (match === ' ') return '&nbsp;'
            if (match === '\t') return '&nbsp;&nbsp;&nbsp;&nbsp;'
            return match
          })
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/([a-zA-Z0-9`~!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+)/g, 
            `<span style="font-family:${this.englishFontFamily};font-size:${this.englishFontSize}.0pt;mso-ascii-font-family:${this.englishFontFamily};mso-hansi-font-family:${this.englishFontFamily};">$1</span>`)
      }

      const codeBlockHtml = `
        <html xmlns:o="urn:schemas-microsoft-com:office:office"
              xmlns:w="urn:schemas-microsoft-com:office:word"
              xmlns="http://www.w3.org/TR/REC-html40">
        <head>
        <meta http-equiv=Content-Type content="text/html; charset=utf-8">
        <style>
        @list l0:level1{
          mso-level-number-format:decimal;
          mso-level-suffix:space;
          mso-level-text:"%1.";
          mso-level-tab-stop:21.0000pt;
          mso-level-number-position:left;
          margin-left:21.0000pt;
          text-indent:-10.5000pt;
          font-family:'${this.englishFontFamily}';
        }
        ol {
          margin: 0;
          padding: 0;
          list-style-type: decimal;
          counter-reset: item;
        }
        li {
          margin: 0;
          padding: 3pt 0 3pt 4pt;
          border-left: 2.25pt solid rgb(108,226,108);
          font-family: ${this.chineseFontFamily};
          font-size: ${this.chineseFontSize}.0pt;
          line-height: 1.2;
          text-indent: -12pt;
          margin-left: 6pt;
        }
        li:nth-child(even) {
          background: rgb(248,248,248);
        }
        li:nth-child(odd) {
          background: rgb(255,255,255);
        }
        li::marker {
          font-family: ${this.englishFontFamily};
          font-size: ${this.englishFontSize}.0pt;
          color: rgb(0,0,0);
        }
        </style>
        </head>
        <body>
          <ol>
            ${this.codeLines.map(line => `
              <li><span style="font-family:${this.chineseFontFamily};font-size:${this.chineseFontSize}.0pt;">${processLine(line)}</span></li>
            `).join('')}
          </ol>
        </body>
        </html>
      `
      
      console.log('复制的Word格式内容：')
      console.log(codeBlockHtml)
      
      tempDiv.innerHTML = codeBlockHtml
      tempDiv.style.position = 'fixed'
      tempDiv.style.left = '-9999px'
      document.body.appendChild(tempDiv)
      
      const range = document.createRange()
      range.selectNode(tempDiv)
      const selection = window.getSelection()
      selection.removeAllRanges()
      selection.addRange(range)
      
      try {
        document.execCommand('copy')
        this.showCopySuccess = true
        setTimeout(() => {
          this.showCopySuccess = false
        }, 2000)
      } catch (err) {
        console.error('复制失败:', err)
      }
      
      selection.removeAllRanges()
      document.body.removeChild(tempDiv)
    }
  }
}
</script>

<style scoped>
.code-converter {
  padding: 0 1rem;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  gap: 2rem;
  padding: 0 1rem;
}

.input-section, .output-section {
  flex: 1;
  min-width: 0;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 1rem;
  background: #f8f9fa;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: var(--text-color);
}

.card-footer {
  padding: 1rem;
  background: #f8f9fa;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
}

.code-input {
  width: 100%;
  height: 500px;
  padding: 1rem;
  font-family: 'Fira Code', 'Courier New', Courier, monospace;
  border: none;
  resize: none;
  font-size: 0.9rem;
  line-height: 1.5;
  color: var(--text-color);
}

.code-input:focus {
  outline: none;
}

.convert-btn, .copy-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: transform 0.2s;
}

.convert-btn {
  background: var(--primary-color);
  color: white;
}

.copy-btn {
  background: var(--secondary-color);
  color: white;
}

.convert-btn:hover, .copy-btn:hover {
  transform: translateY(-1px);
}

.btn-icon {
  font-size: 1.1rem;
}

.word-style-output {
  height: 500px;
  overflow: auto;
  padding: 1rem;
  background-color: #F6F8FA;
  border-radius: 4px;
  margin: 0.5rem;
  font-family: "Times New Roman", SimSun, "宋体", serif;
}

.code-table {
  width: 100%;
  border-collapse: collapse;
  font-family: "Times New Roman", SimSun, "宋体", serif;
  font-size: 0.9rem;
  line-height: 1.5;
  background-color: #F6F8FA;
}

.line-number {
  width: 50px;
  text-align: right;
  padding-right: 1rem;
  color: #6c757d;
  user-select: none;
  border-right: 1px solid #E1E4E8;
  background-color: #F0F2F4;
  position: sticky;
  left: 0;
  font-family: "Courier New", monospace;
}

.code-content {
  padding: 0.25rem 1rem;
  white-space: pre;
  color: #24292e;
  background-color: #F6F8FA;
  font-family: "Times New Roman", SimSun, "宋体", serif;
}

.code-table tr:hover {
  background-color: #EBF0F4;
}

.code-table tr:hover .line-number {
  background-color: #E5E8EA;
}

.code-table tr:nth-child(even) {
  background-color: #F8FAFC;
}

.word-style-output::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.word-style-output::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.word-style-output::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.word-style-output::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.copy-success {
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: var(--secondary-color);
  color: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }
  
  .code-input, .word-style-output {
    height: 300px;
  }

  .word-style-output {
    margin: 0.25rem;
    padding: 0.5rem;
  }
}

.font-settings {
  display: flex;
  gap: 1rem;
  align-items: center;
  margin: 0 1rem;
  flex-wrap: wrap;
}

.setting-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.font-select {
  padding: 0.25rem;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  font-size: 0.9rem;
}

.font-size-input {
  width: 50px;
  padding: 0.25rem;
  border-radius: 4px;
  border: 1px solid var(--border-color);
  font-size: 0.9rem;
}

.card-header {
  flex-wrap: wrap;
  gap: 0.5rem;
}

.shortcut-tips {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  margin-top: 0.5rem;
}

.tip {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.85rem;
  color: #666;
}

.shortcut-key {
  background: #e9ecef;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-family: 'Consolas', monospace;
  border: 1px solid #dee2e6;
}

.tip-text {
  color: #495057;
}
</style> 